package com.common.app.utls

import com.common.app.data.bean.KeyEvents.KEY_TIME_EVENT
import com.common.base.utils.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import java.util.*
import kotlin.collections.HashMap

object TimerUtils {

    //定时器
    private var timerTask: TimerTask? = null

    //定时器是否已经取消
    private var isTimerCancel = false

    //不同页面的计数值
    private val timeValueMap = HashMap<String, Int>()

    /**
     * 启动定时器
     */
    fun startTimer() {
        timerTask?.cancel()
        isTimerCancel = true
        if (timerTask == null || isTimerCancel) {
            timerTask = object : TimerTask() {
                override fun run() {
                    timeValueMap.forEach {
                        timeValueMap[it.key] = it.value + 1
                    }
//                    LogUtils.e("TimerUtils", "task run")
                    LiveEventBus.get(KEY_TIME_EVENT).post(0)
                }
            }
            Timer().scheduleAtFixedRate(timerTask, 0, 1000)//一秒钟跑一次
        }
    }

    /**
     * 停止定时器
     */
    fun cancelTimer() {
        timerTask?.cancel()
        timeValueMap.clear()
        isTimerCancel = true
    }

    /**
     * 获取定时器计数值
     */
    fun getTimerStep(key: String): Int {
        return timeValueMap[key] ?: -1
    }

    /**
     * 添加计时器类型
     */
    fun addTimerKey(key: String) {
        timeValueMap[key] = 0
    }

    /**
     * 取消定时器类型
     */
    fun removeTimer(key: String) {
        timeValueMap.remove(key)
    }

}